﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ITJZ.BitHelper.Local.UI;
using System.Xml;
using ITJZ.BitHelper.Tools;
using ITJZ.BitHelper.APIModel;
using System.IO;

namespace ITJZ.BitHelper.Local.API
{
    public class User : IAPI.IUser
    {
        private static APIModel.User curUser = null;
        public static APIModel.User CurUser
        {
            get 
            {
                if (curUser==null)
                {
                    frmLogin fl = new frmLogin();
                    fl.ShowDialog();
                }
                
                return User.curUser; 
            }
            set
            {
                User.curUser = value;
            }
        }



        #region IUser 成员

        public APIModel.User Login(string email, string password)
        {
            string address = Config.ApiUrl + "?class=User&action=Login";
            string post = string.Format("email={0}&password={1}", email, password);
            string reply = HttpHelper.UploadString(address, post);


            try
            {
                APIModel.User user = XmlSerializerHelper.DeSerialize(typeof(APIModel.User), reply) as APIModel.User;
                if (user==null)
                {
                    throw new Exception();
                }

                User.CurUser = user;
                return user;
            }
            catch
            {
                throw new Exception("登录异常（本地）");
            }
        }

        public ITJZ.BitHelper.APIModel.ResInfo Register(string email, string password)
        {
            string address = Config.ApiUrl + "?class=User&action=Login";
            string reply = HttpHelper.GetString(address);

            try
            {
                APIModel.ResInfo res = XmlSerializerHelper.DeSerialize(typeof(APIModel.ResInfo), reply) as APIModel.ResInfo;
                return res;
            }
            catch
            {
                throw new Exception("出现异常（本地）");
            }           
        }

        #endregion

        internal void Login()
        {
            string[] str = File.ReadAllLines("User");

            string username = str[0];
            string password = str[1];

            this.Login(username, password);
        }
    }
}